//
//  ScanViewController.m
//  TaoOne
//
//  Created by 王里 on 11-7-28.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "ZbarScanViewController.h"
#import "QREncoder.h"
#import "DataMatrix.h"
#import "QRCodeData.h"
#import "AppDelegate.h"
#import "DataMatrix.h"

@interface ZbarScanViewController(privatez)
-(NSString*)encodeNSStringtoUTF8_HexStr:(NSString*)srcstr;
-(NSString*)encodeToPercentEscapeString:(NSString*)input;
-(void) toggleFlashlight;
-(int) checkContent:(NSString*)content;
@end

@implementation ZbarScanViewController
- (void)dealloc
{
    [flashlightButton release];
    [AVSession release];
    [reader release];
    [super dealloc];
}

-(void) startScan{
    p_LightIsOn = 0;
    reader = [ZBarReaderViewController new];
    reader.readerView.torchMode = 0;
    [reader retain];
    reader.readerDelegate = self;
    
    ZBarImageScanner *scanner = reader.scanner;
    
    // TODO: (optional) additional reader configuration here
    
    // EXAMPLE: disable rarely used I2/5 to improve performance
    [scanner setSymbology: ZBAR_I25
                   config: ZBAR_CFG_ENABLE
                       to: 0];
    
    //add red line
    CALayer* tRedLine = [CALayer layer];
    tRedLine.frame =CGRectMake(0, 0, 320, ScreenHeight-50);
    UIImage* tBGImg =[UIImage imageNamed:@"背景透明.png"];
    tRedLine.contents = (id)tBGImg.CGImage;
    
    CALayer* tLogoLine = [CALayer layer];
    tLogoLine.frame =CGRectMake(60, 40, 200, 30);
    UIImage* tLogoImg =[UIImage imageNamed:@"logo.png"];
    tLogoLine.contents = (id)tLogoImg.CGImage;
    
    [reader.view.layer addSublayer:tRedLine];
    [reader.view.layer addSublayer:tLogoLine];
    UIButton* flashbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    [flashbutton addTarget:self action:@selector(turnOffOrOnLight) forControlEvents:UIControlEventTouchUpInside];
    [flashbutton setImage:[UIImage imageNamed:@"闪光灯.png"] forState:UIControlStateNormal];
    flashbutton.frame =CGRectMake(250, 10, 60, 30);
    [reader.view addSubview:flashbutton];
    
    [self.navigationController popToRootViewControllerAnimated:NO];
    [self.navigationController pushViewController:reader animated:YES];
    
    for (id object in [reader.view subviews]) {
        NSLog(@"object =%@",[object description]);
        if ([object isKindOfClass:[UIView class]]) {
            for (id object2 in [(UIView*)object subviews]) {
                NSLog(@"object2 =%@",[object2 description]);
                if ([object2 isKindOfClass:[UIButton class]]) {
                    [object2 removeFromSuperview];
                }
                else if([object2 isKindOfClass:[UIToolbar class]]){
                    for (id object3 in [object2 subviews]) {
                        NSLog(@"object3 =%@",[object3 description]);
                        if ([object3 isKindOfClass:[UIButton class]]) {
                            NSLog(@"123");
                        }
                    }
                    NSArray* tItems = ((UIToolbar*)object2).items; 
                    UIBarButtonItem* bars = [tItems objectAtIndex:0];
                    UIBarButtonItem* newBar = [[UIBarButtonItem alloc] initWithTitle:@"取消扫描" style:UIBarButtonItemStyleBordered target:bars.target action:bars.action];
                    ((UIToolbar*)object2).items = [NSArray arrayWithObjects:newBar,nil];
                }
            }
        }
    }
}

-(void)turnOffOrOnLight{
    if (p_LightIsOn == 0) {
        p_LightIsOn =1;
    }else{
        p_LightIsOn = 0;
    }
    reader.readerView.torchMode = p_LightIsOn;
}

static NSString* tLastScan =@"";

- (void) imagePickerController: (UIImagePickerController*) treader
 didFinishPickingMediaWithInfo: (NSDictionary*) info
{
    
    // ADD: get the decode results
    id<NSFastEnumeration> results =
    [info objectForKey: ZBarReaderControllerResults];
    ZBarSymbol *symbol = nil;
    for(symbol in results)
        // EXAMPLE: just grab the first barcode
        break;
    
    //    // EXAMPLE: do something useful with the barcode data
    NSString* codestr = symbol.data;
    if ([tLastScan isEqualToString:codestr]) {
        return;
    }
    [tLastScan release];
    tLastScan = nil;
    tLastScan = codestr;
    [tLastScan retain];
        NSLog(@"codestr =%@",codestr);
    int jumptype = [self checkContent:codestr];
    switch (jumptype) {
        case 0://网站
        {
            
        }
            break;
        case 1://电话号码
        {
            
        }
            break;
        case 2://地理
        {
            
        }
            break;
        case 3://电邮
        {
            
        }
            break;
        case 4://联系人
        {
            
        }
            break;
        case 5://短信
        {
            
        }
            break;
        case 6://文本
        {
            
        }
            break;
            
    }
//    AppDelegate* tDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate; 
//    QRCodeData* tEpubBook = (QRCodeData*)[NSEntityDescription insertNewObjectForEntityForName:@"QRCodeData" inManagedObjectContext:tDelegate.managedObjectContext];
//    tEpubBook.content = codestr;
//    
//    NSURL* tURL = [NSURL URLWithString:codestr];
//    if (tURL != nil) {
//        tEpubBook.qrtypename =@"网站地址";
//    }else if([codestr rangeOfString:@"@"].location != NSNotFound){
//        tEpubBook.qrtypename =@"电邮地址";
//    }else{
//        tEpubBook.qrtypename =@"其他";
//    }
//    NSDate* myNSDateInstance =[NSDate date];
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yyyy-MM-dd"];
//    
//    //Optionally for time zone converstions
//    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];
//    
//    NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
//    
//    [formatter release];
//    NSLog(@"stringFromDate =%@",stringFromDate);
//    tEpubBook.grouptime =stringFromDate;
//    
//    
//    NSFileManager* tFileMan = [NSFileManager defaultManager];
//    NSString* tMenuPathDoc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//    NSUserDefaults* tDefaults =[NSUserDefaults standardUserDefaults];
//    int index = [[tDefaults objectForKey:@"addsavecount"] intValue];
//    NSString* tSavePath = [tMenuPathDoc stringByAppendingPathComponent:@"QRScanSave"];
//    [tFileMan createDirectoryAtPath:tSavePath withIntermediateDirectories:YES attributes:nil error:nil];
//    
//    NSString* tSaveIndexPath = [tSavePath stringByAppendingPathComponent:[NSString stringWithFormat:@"qrimg%d",index+1]];
//    [tDefaults setValue:[NSNumber numberWithInt:index+1] forKey:@"addsavecount"];
//    
//    DataMatrix* qrMatrix = [QREncoder encodeWithECLevel:QR_ECLEVEL_AUTO version:QR_VERSION_AUTO string:codestr];
//    
//    int qrcodeImageDimension = 300;
//    //then render the matrix
//    UIImage* qrcodeImage = [QREncoder renderDataMatrix:qrMatrix imageDimension:qrcodeImageDimension];
//    [UIImagePNGRepresentation(qrcodeImage) writeToFile:tSaveIndexPath atomically:YES];
//    tEpubBook.qrcodepath =tSaveIndexPath;
//    if (tEpubBook != nil) {
//        NSLog(@"%@",[tEpubBook description]);
//        NSError* error;
//        if (![[tDelegate managedObjectContext] save:&error]) {
//            NSLog(@"save error");
//        }else{
//            NSLog(@"save ok");
//        }
//    }

//    UIAlertView* tAlert =[[UIAlertView alloc] initWithTitle:@"提示" message:@"保存扫描QR图成功" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
//    [tAlert show];
//    [tAlert release];
//    
//    if (tURL != nil) {
//        self.navigationController.navigationBar.hidden =NO;
//        UIViewController* tNext = [[UIViewController alloc] init];
//        UIWebView* tWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-44-50)];
//        [tWebView loadRequest:[NSURLRequest requestWithURL:tURL]];
//        [tNext.view addSubview:tWebView];
//        [tWebView release];
//        [self.navigationController pushViewController:tNext animated:YES];
//        [tNext release];
//        self.navigationController.navigationBar.topItem.hidesBackButton =YES;
//    }

}

- (NSString *)encodeToPercentEscapeString: (NSString *) input  
{  
    // Encode all the reserved characters, per RFC 3986  

    NSString *outputStr = (NSString *)   
    CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,  
                                            (CFStringRef)input,  
                                            NULL,  
                                            (CFStringRef)@"!*'();:@&=+$,/?%#[]",  
                                            kCFStringEncodingUTF8);  
    return outputStr;  
}


-(int) checkContent:(NSString*)content{
    AppDelegate* tDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate; 
    QRCodeData* tEpubBook = (QRCodeData*)[NSEntityDescription insertNewObjectForEntityForName:@"QRCodeData" inManagedObjectContext:tDelegate.managedObjectContext];
    tEpubBook.content = content;
    NSString* tDoStr = [content lowercaseString];
    int state = 0;
    //网站
    NSURL* tURL = [NSURL URLWithString:tDoStr];
    if (tURL != nil) {
        tEpubBook.qrtypename =@"网站地址";
        goto writeSql;
    }
    //电话号码
    if ([[tDoStr substringWithRange:NSMakeRange(0, 4)] isEqualToString:@"tel:"]) {
        tEpubBook.qrtypename =@"电话号码";
        goto writeSql;
    }
    //地理
    if ([[tDoStr substringWithRange:NSMakeRange(0, 4)] isEqualToString:@"geo:"]) {
        tEpubBook.qrtypename =@"地理位置";
        goto writeSql;
    }
    //电邮
    if ([[tDoStr substringWithRange:NSMakeRange(0, 7)] isEqualToString:@"mailto:"]) {
        tEpubBook.qrtypename =@"邮件地址";
        goto writeSql;
    }
    //mecard
    if ([[tDoStr substringWithRange:NSMakeRange(0, 7)] isEqualToString:@"mecard:"]) {
        tEpubBook.qrtypename =@"Mecard联系人";
        goto writeSql;
    }
    //信息
    if ([[tDoStr substringWithRange:NSMakeRange(0, 6)] isEqualToString:@"smsto:"]) {
        tEpubBook.qrtypename =@"电话号码";
        goto writeSql;
    }
    //文本
    tEpubBook.qrtypename =@"文本";
    
writeSql:    
    //写数据库
    NSDate* myNSDateInstance =[NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    //Optionally for time zone converstions
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];
    
    NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
    
    [formatter release];
    NSLog(@"stringFromDate =%@",stringFromDate);
    tEpubBook.grouptime =stringFromDate;
    
    
    NSFileManager* tFileMan = [NSFileManager defaultManager];
    NSString* tMenuPathDoc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSUserDefaults* tDefaults =[NSUserDefaults standardUserDefaults];
    int index = [[tDefaults objectForKey:@"addsavecount"] intValue];
    NSString* tSavePath = [tMenuPathDoc stringByAppendingPathComponent:@"QRScanSave"];
    [tFileMan createDirectoryAtPath:tSavePath withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSString* tSaveIndexPath = [tSavePath stringByAppendingPathComponent:[NSString stringWithFormat:@"qrimg%d",index+1]];
    [tDefaults setValue:[NSNumber numberWithInt:index+1] forKey:@"addsavecount"];
    
    DataMatrix* qrMatrix = [QREncoder encodeWithECLevel:QR_ECLEVEL_AUTO version:QR_VERSION_AUTO string:content];
    
    int qrcodeImageDimension = 300;
    //then render the matrix
    UIImage* qrcodeImage = [QREncoder renderDataMatrix:qrMatrix imageDimension:qrcodeImageDimension];
    [UIImagePNGRepresentation(qrcodeImage) writeToFile:tSaveIndexPath atomically:YES];
    tEpubBook.qrcodepath =tSaveIndexPath;
    if (tEpubBook != nil) {
        NSLog(@"%@",[tEpubBook description]);
        NSError* error;
        if (![[tDelegate managedObjectContext] save:&error]) {
            NSLog(@"save error");
        }else{
            NSLog(@"save ok");
        }
    }
    
    return state;
}

@end
